import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.datasets import make_regression
import matplotlib.pyplot as plt

# 设置全局字体为黑体（SimHei）
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用黑体显示中文
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题
# 生成具有明显线性关系的模拟数据
np.random.seed(42)
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)

# 可视化数据
plt.figure(figsize=(10, 6))
plt.scatter(X, y, alpha=0.7, label='原始数据')
plt.xlabel('X - 自变量')
plt.ylabel('y - 因变量')
plt.title('模拟数据散点图')
plt.legend()
plt.grid(True)
plt.show()

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建线性回归模型
model = LinearRegression()

# 训练模型
model.fit(X_train, y_train)

# 输出模型参数
print(f"截距(β₀): {model.intercept_[0]:.4f}")
print(f"系数(β₁): {model.coef_[0][0]:.4f}")

# 在测试集上进行预测
y_pred = model.predict(X_test)

# 计算评估指标
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print(f"\n模型评估:")
print(f"均方误差(MSE): {mse:.4f}")
print(f"R²分数: {r2:.4f}")

# 可视化预测结果
plt.figure(figsize=(10, 6))
plt.scatter(X_test, y_test, color='blue', label='真实值')
plt.plot(X_test, y_pred, color='red', linewidth=2, label='预测值')
plt.xlabel('X - 自变量')
plt.ylabel('y - 因变量')
plt.title('线性回归预测结果')
plt.legend()
plt.grid(True)
plt.show()

# 生成多变量回归数据
X_multi, y_multi = make_regression(n_samples=100, n_features=3, noise=10, random_state=42)

# 划分训练测试集
X_train_m, X_test_m, y_train_m, y_test_m = train_test_split(X_multi, y_multi, test_size=0.2, random_state=42)

# 创建并训练模型
multi_model = LinearRegression()
multi_model.fit(X_train_m, y_train_m)

# 评估模型
y_pred_m = multi_model.predict(X_test_m)
mse_m = mean_squared_error(y_test_m, y_pred_m)
r2_m = r2_score(y_test_m, y_pred_m)

print("\n多变量线性回归结果:")
print(f"截距: {multi_model.intercept_:.4f}")
print(f"系数: {multi_model.coef_}")
print(f"均方误差(MSE): {mse_m:.4f}")
print(f"R²分数: {r2_m:.4f}")